/**
 * 重写toFixed方法，防止部分四舍五入不对的情况
 * @param {Number} num
 * @param {Number} accuracy
 * @return {String}
 */
const toFixed = (num, accuracy) => {
  let times = Math.pow(10, parseInt(accuracy) + 1);
  let des = parseInt(num * times);
  let rest = des % 10;
  if (rest == 5) {
    return ((parseFloat(des) + 1) / times).toFixed(accuracy);
  }
  return num.toFixed(accuracy);
};

/**
 *
 * 格式化金额
 * @param {number | string} number 格式化数字
 * @param {number | string} accuracy 格式化位数
 * @return {String}
 */
const formatMoney = (number, accuracy = 2) => {
  number = isNaN(parseFloat(number)) ? 0 : parseFloat(number);
  if (number.toString().includes('e')) {
    return number.toString();
  }
  accuracy = parseInt(accuracy);
  const temp = [];
  const isPositive = number >= 0;
  const _number = toFixed(Math.abs(number), accuracy);
  let [intDigit, decimalDigit] = _number.split('.');
  const padZero = (value, length) =>
    `${new Array(length).fill('0').join('')}${String(value)}`.substr(-length);
  do {
    temp.unshift(padZero(intDigit % 1000, 3));
  } while ((intDigit = parseInt(intDigit / 1000)));

  temp[0] = parseInt(temp[0]).toString();

  return `${isPositive ? '' : '-'}${temp.join(',')}${
    accuracy == 0 ? '' : `.${padZero(decimalDigit || '', accuracy)}`
  }`;
};

/**
 * 根据企业参数格式化数字
 * @param {Number} value
 * @param {Number} accuracy
 * @param {Boolean} isNum
 * @return {String}
 */
export const formatNumber = (value = 0, accuracy, isNum) => {
  let oValue = unformatNumber(value);
  if (isNum != true) {
    return formatMoney(oValue, accuracy);
  } else {
    return toFixed(Number(oValue), accuracy);
  }
};

/**
 * 将被格式化的数字转为数字，任意无法被认为是数字的都会变成0
 * @param {String|Number} value
 * @return {Number}
 */
export const unformatNumber = value => {
  const number = parseFloat(String(value).replace(/,/g, ''));
  return isNaN(number) ? 0 : number;
};
